package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hemabox/models/cache"
	"hemabox/models/mysql"
	"time"

	"hemabox/hemarpc/hemarpc"
	"hemabox/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HemaListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHemaListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HemaListLogic {
	return &HemaListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表
func (l *HemaListLogic) HemaList(in *hemarpc.HemaListRequest) (*hemarpc.HemaListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*hemarpc.HemaList

	data := fmt.Sprintf("hemaList_%d", in.Page)
	result, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if result == "" {
		var err error
		list, err = mysql.HemaList(mysql.DB, in)
		if err != nil {
			return nil, errors.New("查询失败")
		}
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, data, marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &hemarpc.HemaListResponse{
		List: list,
	}, nil
}
